/**
 * Created by shenhai on 15/10/15.
 */


var async = require('async');
var User = mongoose.model('user');
var Community = mongoose.model('community');
var RoleApply = mongoose.model('user_role_apply');
var toolUtil = require('../../../common/utils/toolUtil');
var UserCommunity = mongoose.model('user_community');
var UserInvitation = mongoose.model('user_invitation');
var Question = mongoose.model('question');
/*  宝宝树66小区二次改造    mod   chenf  20170802  start   */
// 大使小区关联model
var ambassadorCommunity = mongoose.model('ambassador_community');
var moment = require('moment');
// 用户id
var userId = null;
/*  宝宝树66小区二次改造    mod   chenf  20170802  end   */
Array.prototype.addNonrepeat = function (element) {

    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return this;
        }
    }

    this.push(element);
    return this;
};


exports.roleApplyListService = function (req, callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option = body;
    var sortType = {dateCreated: -1};

    var data = [];
    logger.debug(option);

    if (option.city) {
        if (option.city === '0') option.city = '54d862bb573a6d301441b94f';
        else option.city = {$ne: '54d862bb573a6d301441b94f'};
    }

    var tmpUser = option.user;
    if(tmpUser) {
        try{
            var id = mongoose.Types.ObjectId(tmpUser);
        } catch (e) {
            logger.error(tmpUser + '不是合法的mongodb的id');
            callback(e, null);
        }
    }

    async.series([
        function (callbackInner) {
            RoleApply.count(option, function (err, count) {

                totalPage = Math.ceil(count / size);
                var temp = {count: count, totalPage: totalPage};
                callbackInner(err, temp);

            });
        },
        function (callbackInner) {
            RoleApply.find(option).sort(sortType).skip(index).limit(size)
                .populate('user', '_id nickName community huanxinUserName mobilePhone realName wxName')
                .populate('community', '_id communityName cityId city')
                .exec(function (err, result) {

                    async.eachSeries(result, function (temp, callbackInner2) {

                        temp._doc.user._doc.huanxinUserName = temp.user.huanxinUserName;

                        async.series([
                            function (callbackInner3) {
                                var key = 'user:' + temp.user + ':app:data:statistic';
                                var opt = [key, 'question', 'questionReply', 'praise', 'goods'];
                                redisClient.hmget(opt, function (err, result) {
                                    temp._doc.questionCount = result[0] ? result[0] : 0;
                                    temp._doc.replyCount = result[1] ? result[1] : 0;
                                    temp._doc.praiseCount = result[2] ? result[2] : 0;
                                    temp._doc.goodsCount = result[3] ? result[3] : 0;
                                    //data.push(temp);
                                    callbackInner3(err, temp);
                                });
                            },

                            function (callbackInner3) {

                                UserInvitation.find({inviter: temp.user._id}).populate('inviter', '_id community').populate('invitee', '_id community')
                                    .exec(function (err, result) {
                                        temp._doc.inviteeCount = result.length;
                                        temp._doc.inviteeCount_Community = 0;
                                        result.forEach(function (invit) {
                                            if (invit.inviter.community + '' == invit.invitee.community + '') {
                                                temp._doc.inviteeCount_Community++;
                                            }
                                        });
                                        data.push(temp);
                                        callbackInner3(err, result);
                                    });
                            },
                        ], callbackInner2);

                    }, function (err, result) {
                        callbackInner(err, data);
                    });
                });
        }
    ], callback);

};


exports.roleApplyStatusService = function (req, callback) {

    var ip = req.headers['X-Real-IP'];
    var id = req.body.id;
    var user = req.body.user._id;
    var huanxinUserName = req.body.user.huanxinUserName;
    var status = req.body.status;
    var type = req.body.type;
    var msg = req.body.msg;
    var currntCommunity = req.body.user.community;
    var applyCommunity = req.body.applyCommunity;
    var applyCommunityName = req.body.applyCommunityName;

    <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start -->
    var operateType = req.body.operateType;
    <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end -->

    var role;
    var userRole = [];
    if (type == 1) role = 1;  // 申请版主
    else if (type == 2) role = 3;  // 申请雷锋团
    else if (type == 4) role = 4; // 申请创建人
    logger.debug(req.body);
    //申请时小区和用户当前小区相同
    if (applyCommunity == currntCommunity) {
        async.series([
            /*  宝宝树66小区二次改造    mod   gct  20170811  start   */
            function (callbackInner)
            {
                if(status)
                {
                    RoleApply.findOne({community: currntCommunity,status: 1}).exec(function(err,result)
                    {
                        if (err) {
                            callbackInner(err, result);
                        } else {
                            if(result != null) {
                                callbackInner({status:999,message:"本小区已有小区大使！"});
                            } else {
                                ambassadorCommunity.findOne({community: currntCommunity, isValid: true})
                                    .exec(function(err,result) {
                                        if (err) {
                                            callbackInner(err);
                                        } else if (result != null) {
                                            callbackInner({status:999,message:"本小区已有小区大使！"});
                                        } else {
                                            callbackInner();
                                        }
                                });
                            }
                        }
                    });
                } else {
                    callbackInner();
                }
            },
            /*  宝宝树66小区二次改造    mod   gct  20170811  end   */

        function (callbackInner) {
            /*  宝宝树66小区二次改造    mod   gct  20170811   start   */
            // RoleApply.update({_id: id}, {status: status ? 1 : -1},callbackInner);

            <!--  宝宝树66小区四次改造 追加申请通过日期，取消日期 mod   guo.xiaomin  20171027  start   -->
            var setOpt = {};
            if(status) { // 通过大使申请(小于等于2038年某一天为有效时间)
                var endDateTime = new Date(moment("2038-01-01", "YYYY-MM-DD").format());
                setOpt = {status: status ? 1 : -1, startDateTime : new Date(), endDateTime : endDateTime};
            } else { // 拒绝或者取消大使申请
                <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start -->
                if (operateType == 'cancel') { // 取消大使
                    setOpt = {status: status ? 1 : -1, cancelReason: msg, endDateTime : new Date()};
                } else if (operateType == 'decline') { // 拒绝申请
                    var roleApplyStatus = req.body.roleApplyStatus;
                    setOpt = {status: status ? 1 : roleApplyStatus, cancelReason: msg, endDateTime : new Date()};
                }
                <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end -->
            }
            RoleApply.update({_id: id}, setOpt) .exec(function (err, roleResult) { // 新
            // RoleApply.update({_id: id}, {status: status ? 1 : -1}) .exec(function (err, roleResult) { // 旧
            <!--  宝宝树66小区四次改造 追加申请通过日期，取消日期 mod   guo.xiaomin  20171027  end   -->
                if(!status)
                {
                    ambassadorCommunity.update({user: user}, {isValid: false},{multi:true}, callbackInner);
                } else {
                    callbackInner();
                }
            });
            /*  宝宝树66小区二次改造    mod   gct  20170811   end   */
        },

        function (callbackInner) {

            if (status) {
                User.findOne({_id: user}, function (err, result) {
                    if (result.userRole) userRole = result.userRole;
                    userRole.addNonrepeat(role);
                    callbackInner(err, result);
                });
            } else {
                callbackInner();
            }
        },

        function (callbackInner) {

            if (type == 4) {
                userRole.addNonrepeat(1);
            }
            if (status) {
                User.update({_id: user}, {userRole: userRole}, callbackInner);
            } else {
                /*  宝宝树66小区二次改造    add   gct  20170731   start   */
                userRole = [];
                User.update({_id: user}, {userRole: userRole}, callbackInner);
                // callbackInner();
                /*  宝宝树66小区二次改造    add   gct  20170731   end   */
            }
        },

        function (callbackInner) {
            if (status) {
                UserCommunity.update({
                    user: user,
                    community: currntCommunity
                }, {$set: {'userRole': userRole}}, callbackInner);
            } else {
                /*  宝宝树66小区二次改造    mod   gct  20170731   start   */
                userRole = [];
                UserCommunity.update({
                    user: user,
                    community: currntCommunity
                }, {$set: {'userRole': userRole}}, callbackInner);
                // callbackInner();
                /*  宝宝树66小区二次改造    mod   gct  20170731   end   */
            }
        },

        function (callbackInner) {

            if (status) {

                toolUtil.setUserByToken(user);

                //个推
                var content = {
                    f: 8,
                    userRole: role
                };
                var pushData = {
                    uList: [user],
                    content: content
                };
                //logger.debug(pushData);
                toolUtil.putMessageTransmissionPushMQ(pushData);
            }
            callbackInner();
        },

        function (callbackInner) {

            if (type == 1) {

                if (status) { // 通过

                    // XXX成功成为小区管理员喽，快去勾搭一下TA吧～  // 推送
                    User.find({community: req.body.user.community, _id: {$ne: user}})
                        .exec(function (err, result) {

                            if (result) {
                                var userList = [];
                                if (result) {
                                    for (user in result) {
                                        userList.push(result[user]._id);
                                    }
                                }
                                var content = {
                                    type: 1,
                                    flag: 2,
                                    openType: 10,
                                    contentId: req.body.user._id,
                                    //createdBy: input.createdBy,
                                    desc: req.body.user.nickName + '顺利晋升小区管理员咯，试试关注TA, 小区动态早知道哦！'
                                    //url: input.url
                                };
                                var pushData = {
                                    uList: userList,
                                    content: content,
                                    ip: req.headers['X-Real-IP'],
                                    //tag: input.tag,
                                    type: 'operate',
                                    msgType: 2
                                };
                                //logger.debug(pushData);
                                toolUtil.putMessageGetuiPushMQ(pushData);
                            }
                        });

                    toolUtil.pushCustomerServiceMessage({
                        _id: user,
                        huanxinUserName: huanxinUserName
                    }, '恭喜你成功摘得管理员桂冠,邻里建设都要靠你多多关照啦！');
                } else {  // 拒绝
                    toolUtil.pushCustomerServiceMessage({_id: user, huanxinUserName: huanxinUserName}, msg);
                }

            } else if (type == 2) {

                if (status) {  // 通过
                    toolUtil.pushCustomerServiceMessage({
                        _id: user,
                        huanxinUserName: huanxinUserName
                    }, '恭喜你，成为宝宝树66小区雷锋团的一员。');
                } else {  // 拒绝
                    toolUtil.pushCustomerServiceMessage({_id: user, huanxinUserName: huanxinUserName}, msg);
                }
            } else if (type == 4) {

                if (status) {  // 通过
                    //toolUtil.pushCustomerServiceMessage({
                    //    _id: user,
                    //    huanxinUserName: huanxinUserName
                    //}, '恭喜你成为了'+applyCommunityName+'的创始人，请努力建设以及管理好你的小区吧！');

                    var pushData = {
                        userId: user,
                        msgType: 'founder'
                    };
                    logger.debug(pushData);
                    toolUtil.putMessageTagPushMQ(pushData);

                    User.findOne({"mobilePhone": "66customerservice"}, '_id', function (err, service) {
                        var temp = new Question();
                        temp.category = 'share';
                        <!-- 宝宝树66小区二次改造    mod   张秘  20170723   start-->
                        /* temp.desc = '恭喜' + req.body.user.nickName + '成为' + applyCommunityName + '小区的创始人，获得1666积分';*/
                        <!-- 宝宝树66小区二次改造    mod   dayu  20170723   start-->
                        //temp.desc = '恭喜' + req.body.user.nickName + '小区居民请注意！即日起' + req.body.user.nickName +'成为'+ applyCommunityName +'小区的小区大使，如果你在小区里发布了优质内容，会被小区大使加精哦，据说，小区大使还能给大家带来很多福利呢，所以还等啥，大家快来本帖评论拜码头啦';
                        temp.desc = applyCommunityName + '小区居民请注意！即日起' + req.body.user.nickName +'成为'+ applyCommunityName +'小区的小区大使，如果你在小区里发布了优质内容，会被小区大使加精哦，据说，小区大使还能给大家带来很多福利呢，所以还等啥，大家快来本帖评论拜码头啦';
                        <!-- 宝宝树66小区二次改造    mod   dayu  20170723   end-->
                        <!-- 宝宝树66小区二次改造    mod   张秘  20170723   end-->
                        temp.createdBy = service._id;
                        temp.community = applyCommunity;
                        temp.city = req.body.applyCityId;
                        temp.fromFlag = 'service';
                        temp.save(function (err, question) {

                            //添加积分
                            var arg = {
                                userId: req.body.user._id + '',
                                userRole: 1,
                                userActionType: 43
                            };

                            arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
                            logger.debug(arg);
                            scoreProxy.invoke('addScore', [arg], function (err, reply) {
                                try {
                                    logger.debug(reply);
                                    var data = JSON.parse(decodeURIComponent(reply));
                                    if (err) {
                                        logger.error('hessianInvokeAddScore-----2' + err.message);
                                        callbackInner(null);
                                    } else if (data.status != 0) {
                                        logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
                                        callbackInner(null);
                                    } else {
                                        callbackInner(null);
                                    }
                                } catch (e) {
                                    logger.error('hessianInvokeAddScore---4' + e);
                                    callbackInner(e);
                                }
                            });

                            //推送帖子
                            User.find({community: applyCommunity}).exec(function (err, result) {

                                logger.debug(result.length);
                                var userList = [];
                                result.forEach(function (user) {
                                    userList.push(user._id);
                                });
                                logger.debug(question);
                                var content = {
                                    type: 1,
                                    flag: 2,
                                    openType: 1,
                                    contentId: temp._id,
                                    createdBy: service._id,
                                    <!-- 宝宝树66小区二次改造    mod   张秘  20170723   start-->
                                    /* desc: '本小区的创始人诞生啦！关注他可了解更多小区信息哦！'*/
                                    <!-- 宝宝树66小区二次改造    mod   张秘  20170723   end-->
                                    desc: '我们小区有新的小区大使啦~速来拜码头'
                                    //url: input.url
                                };

                                var pushData = {
                                    uList: userList,
                                    content: content,
                                    ip: ip,
                                    //tag: body.tag,
                                    type: 'operate',
                                    msgType: 2
                                };
                                //logger.debug(pushData);
                                toolUtil.putMessageGetuiPushMQ(pushData);

                                callback();

                            });


                        });
                    })


                } else {  // 拒绝
                    toolUtil.pushCustomerServiceMessage({_id: user, huanxinUserName: huanxinUserName}, msg);
                }
            }

            callbackInner();
        },

        //function(callbackInner){
        //
        //    var arg = {
        //        userId: req.body.user._id + '',
        //        userRole: 1,
        //        userActionType:  19
        //    };
        //
        //    arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
        //    logger.debug(arg);
        //    scoreProxy.invoke('addScore', [arg], function (err, reply) {
        //        try {
        //            logger.debug(reply);
        //            var data = JSON.parse(decodeURIComponent(reply));
        //            if (err) {
        //                logger.error('hessianInvokeAddScore-----2' + err.message);
        //                callbackInner(null);
        //            } else if (data.status != 0) {
        //                logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
        //                callbackInner(null);
        //            } else {
        //                callbackInner(null);
        //            }
        //        } catch (e) {
        //            logger.error('hessianInvokeAddScore---4' + e);
        //            callbackInner(e);
        //        }
        //    });
        //},


    ], function(err, result){
        logger.info(err+","+ result);
            if (err) {
                callback(err, result);
            }
            callback(err, result);
    });

    } else {
        logger.debug('申请小区和当前小区不同');
        async.series([

            function (callbackInner) {
                /*  宝宝树66小区二次改造    mod   gct  20170811  start   */
                if(status)
                {
                    RoleApply.findOne({community: currntCommunity,status: 1}).exec(function(err,result)
                    {
                        if (err) {
                            callbackInner(err);
                        } else {
                            if(result!=null) {
                                if("undefined"!=typeof (result.name)) {
                                    callbackInner({status:999, message:"本小区已有小区大使！"});
                                } else {
                                    callbackInner();
                                }
                            } else {
                                callbackInner({status:888, message:"本用户已经不再本小区了！"}, result);
                            }
                        }
                    });
                }
                /*  宝宝树66小区二次改造    mod   gct  20170811  end   */
                else {
                    RoleApply.update({_id: id}, {status: status ? 1 : -1}, callbackInner);
                }

               /* RoleApply.update({_id: id}, {status: status ? 1 : -1}, callbackInner);*/
                /*  宝宝树66小区二次改造    add   gct  20170802   start   */
                /*if(!status)
                {
                    userRole = [];
                    User.update({_id: user}, {userRole: userRole}, callbackInner);
                }*/
                /*  宝宝树66小区二次改造    add   gct  20170802   end   */
            },


            function (callbackInner) {

                if (status) {
                    //logger.debug(user);
                    //logger.debug(applyCommunity);
                    UserCommunity.findOne({user: user, community: applyCommunity}, function (err, result) {
                        logger.debug(result);
                        if (result.userRole) userRole = result.userRole;
                        userRole.addNonrepeat(role);
                        callbackInner(err, result);
                    });
                } else {
                    callbackInner();
                }
            },
            function (callbackInner) {
                if (status) {
                    UserCommunity.update({
                        user: user,
                        community: applyCommunity
                    }, {$set: {'userRole': userRole}}, callbackInner);
                } else {
                    /*  宝宝树66小区二次改造    mod   gct  20170802   start   */
                    userRole = [];
                    UserCommunity.update({
                        user: user,
                        community: applyCommunity
                    }, {$set: {'userRole': userRole}}, callbackInner);
                    // callbackInner();
                    /*  宝宝树66小区二次改造    mod   gct  20170802   end   */
                }
            },
            function (callbackInner) {

                if (type == 1) {

                    if (status) { // 通过
                        toolUtil.pushCustomerServiceMessage({
                            _id: user,
                            huanxinUserName: huanxinUserName
                        }, '恭喜你成功摘得' + applyCommunityName + '小区管理员桂冠,邻里建设都要靠你多多关照啦！');
                    } else {  // 拒绝
                        toolUtil.pushCustomerServiceMessage({_id: user, huanxinUserName: huanxinUserName}, msg);
                    }

                } else if (type == 2) {

                    if (status) {  // 通过
                        toolUtil.pushCustomerServiceMessage({
                            _id: user,
                            huanxinUserName: huanxinUserName
                        }, '恭喜你，成为宝宝树66小区雷锋团的一员。');
                    } else {  // 拒绝
                        toolUtil.pushCustomerServiceMessage({_id: user, huanxinUserName: huanxinUserName}, msg);
                    }
                } else if (type == 4) {

                    if (status) {  // 通过
                        toolUtil.pushCustomerServiceMessage({
                            _id: user,
                            huanxinUserName: huanxinUserName
                            /*  宝宝树66小区二次改造    mod   XXX  20170714   start   */
                            /*    }, '恭喜你成为了' + applyCommunityName + '的创始人，请努力建设以及管理好你的小区吧！');*/
                        }, '恭喜你成为了' + applyCommunityName + '小区的小区大使，快去宣誓吧！');
                    } else {  // 拒绝
                        toolUtil.pushCustomerServiceMessage({_id: user, huanxinUserName: huanxinUserName}, msg);
                    }
                }


                callbackInner();
            },

        ], callback);


    }
    logger.debug(req.body);
    //申请时小区和用户当前小区相同
};

/*  宝宝树66小区二次改造    mod   chenf  20170802  start   */
/*小区管理权限设置*/
exports.roleApplyPowerSet = function (req, callback) {
    userId = req.body.userId;
    async.series([
        // 根据userId检索该用户已经在管理的小区
        function (callbackInner) {

            ambassadorCommunity.find({'$and':[{user:userId},{isValid:{"$ne":false}}]})
            .populate('community', '_id communityName cityId city').exec(function (err, result) {
                callbackInner(err,result);
            })
        }
    ],
        function(err, result){
            callback(err,result);
    });
};

/*保存小区分配信息*/
exports.saveCommunitySet = function (req, callback) {
    var community = req.body.user.community;
    async.series([
        /*  宝宝树66小区二次改造    mod   gct  20170823   start   */
        function(callbackInner) {

            //var community = body.user.community;
            // var community = body.user.community; // 旧
            /*  宝宝树66小区二次改造    mod   guo  20170823   start   */
            if (community) {
                callbackInner(null, null);
            }
            else {
                Community.findOne({
                    communityName: req.body.communityValue,
                    isValid: true,
                    cityId: req.body.user.cityId
                }, function (err, result) {
                    if (err) {
                        logger.error(err.message);
                        callbackInner(err, result);
                    }
                    /*  宝宝树66小区二次改造    add   gct  20170823   start   */
                    else if (result == null) {
                        return callback({status: 999, message: "请仔细确认小区名"}, null);
                    }
                    /*  宝宝树66小区二次改造    add   gct  20170823  end */
                    community = result._id;
                    req.body.user.community = community;

                    callbackInner(null, null);


                });

                /* alert("小区："+body.communityValue);*/
            }
        },
        function(callbackInner)
        {
            var option = {'$and': [{community: req.body.user.community}, {user: req.body.userID}]};
            ambassadorCommunity.find(option, function (err, result) {
                // 该用户与该小区有过联系的场合
                if (result != null && result.length > 0) {
                    // 更新该用户和小区的关系
                    ambassadorCommunity.update(option, {'$set': {'isValid': true}}, {multi: true}, function (err) {
                        callback(err);
                    })
                } else {
                    // 插入该用户和小区的关系
                    var tempAmbassadorCommunity = new ambassadorCommunity();
                    tempAmbassadorCommunity.user = req.body.userID;
                    tempAmbassadorCommunity.community = req.body.user.community;
                    tempAmbassadorCommunity.save(function (err) {
                        callback(err);
                    });
                }
            })

        }
    ], callback);

};

/*编辑小区分配信息*/
exports.editCommunitySet = function (req, callback) {
    var option = { '$and':[{community:{'$nin':req.body.community}},{user:req.body.userId}]};
    ambassadorCommunity.update(option,{'$set':{'isValid':false}},{multi:true},function (err) {

        callback(err);
    })
};
// 检索可以分配的小区信息
exports.villageService = function (req, callback) {
    var options = [];
    var user=null;
    async.series([
            // 根据userRole=‘4’并且不是自己的userid检索user表里的 小区id
            function (callbackInner) {
                User.find({userRole: {"$all": [4]}}, function (err, result) {
                    if (result != null && result.length > 0) {
                        result.forEach(function(obj,index,array){
                            options.push(obj._doc.community);
                        });
                    }
                    callbackInner();
                });
            },
            function (callbackInner) {
                // 根据userId ！= 自己的id并且不是删除的的小区id
                ambassadorCommunity.find({isValid:{"$ne":false}}, function (err, result) {
                    if(result != null && result.length>0){
                        result.forEach(function(obj,index,array){
                            options.push(obj._doc.community);
                        });
                    }
                    callbackInner();
                });
            },

            // 检索可以分配的小区信息
            function (callbackInner) {
                var body = req.body;
                var option = { '$and':[{_id:{'$nin':options}},{countyId:body.countyId},{isValid:true}]};
                var sortType = {};
                Community.find(option, '_id communityName').sort(sortType).exec(function (err, results) {
                    callbackInner(err, results);
                });
            }
        ],
        function(err, results){
            callback(err,results[2]);
        });
};

/*  宝宝树66小区二次改造    mod   chenf  20170802  start   */




